package weaver.limitCurrent;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ExpireConcurrentHashMap {
    private static final Map<String, Object> CACHE_MAP = new ConcurrentHashMap<>();
    private static final long CACHE_HOLD_TIME_Scecond = 1000L;
    public static void put(String cacheName, int holdTime) {
        if (checkCacheName(cacheName)) {
            return;
        }
        //缓存失效时间
        CACHE_MAP.put(cacheName + "_HoldTime", System.currentTimeMillis() + holdTime * CACHE_HOLD_TIME_Scecond);
    }
    public static int size(){
        return CACHE_MAP.isEmpty()? 0 : CACHE_MAP.size()/2;
    }

    /**
     * 删除所有缓存
     */
    public static void removeAll() {
        CACHE_MAP.clear();
    }
    public static void remove(String cacheName) {
        CACHE_MAP.remove(cacheName + "_HoldTime");
    }
    /**
     * 检查缓存对象是否存在，
     * 若不存在，则返回false
     * 若存在，检查其是否已过有效期，如果已经过了则删除该缓存并返回false
     *
     * @param cacheName
     * @return
     */
    public static boolean checkCacheName(String cacheName) {
        Long cacheHoldTime = (Long) CACHE_MAP.get(cacheName + "_HoldTime");
        if (cacheHoldTime == null || cacheHoldTime == 0L) {
            return false;
        }
        if (cacheHoldTime < System.currentTimeMillis()) {
            remove(cacheName);
            return false;
        }
        return true;
    }
}
